package com.johnrambo.ktea.ktExtends

import android.app.Activity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import android.content.Context
import android.content.Intent
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity

inline fun <reified T> Context.createIntent() = Intent(this, T::class.java)

inline fun <reified T : Activity> Context.startActivity() = startActivity(Intent(this, T::class.java))

inline fun <reified T : ViewModel> androidx.fragment.app.FragmentActivity.getViewModel() = ViewModelProviders.of(this).get(T::class.java)

inline fun <reified T : ViewModel> androidx.fragment.app.Fragment.getViewModel() = ViewModelProviders.of(this).get(T::class.java)

inline fun <reified T : Activity> androidx.fragment.app.Fragment.startActivity() = activity?.run { startActivity(Intent(this, T::class.java)) }


// 显示一个fragment
fun androidx.fragment.app.FragmentActivity.showFragment(fragment: androidx.fragment.app.Fragment, hiddens: Array<androidx.fragment.app.Fragment>) {
    with(supportFragmentManager) {
        val transaction = beginTransaction()
        for (hidden in hiddens) {
            transaction.hide(hidden)
        }
        transaction.show(fragment)
        transaction.commitAllowingStateLoss()
    }
}

// 把一个fragment数组添加到页面中
fun androidx.fragment.app.FragmentActivity.addFragment(@IdRes containerViewId: Int, fragments: Array<androidx.fragment.app.Fragment>) {
    with(supportFragmentManager) {
        val transaction = beginTransaction()
        for (fragment in fragments) {
            transaction.add(containerViewId, fragment)
        }
        transaction.commitAllowingStateLoss()
    }
}

inline fun <reified T : androidx.fragment.app.FragmentActivity> androidx.fragment.app.Fragment.activity(runnable: T.() -> Unit) {
    activity?.let {
        it as T
        it.runnable()
    }
}

fun Context.dp2px(dps: Int) = Math.round(resources.displayMetrics.density * dps)

fun Context.px2dp(pxs: Int) = Math.round(pxs / resources.displayMetrics.density)

fun androidx.fragment.app.Fragment.dp2px(dps: Int) = activity?.dp2px(dps) ?: 0

fun androidx.fragment.app.Fragment.px2dp(pxs: Int) = activity?.px2dp(pxs) ?: 0

